package com.shop.cereshop.app.service.gaode.impl;

import com.shop.cereshop.app.domain.gaode.GaodePathResponse;
import com.shop.cereshop.app.service.gaode.GaodeMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;

@Service
@Slf4j(topic = "GaodeMapService")
public class GaodeMapServiceImpl implements GaodeMapService {

    @Value("${gaode.key}")
    private String gaodeKey;

    @Value("${gaode.baseUrl}")
    private String baseUrl;

    @Value("${gaode.bicycling}")
    private String bicyclingPath;

    @Value("${gaode.walking}")
    private String walkingPath;

    @Value("${gaode.driving}")
    private String drivingPath;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 调用高德地图骑行路径规划API
     *
     * @param origin      起点经纬度 (格式: x,y)
     * @param destination 终点经纬度 (格式: x,y)
     * @return 路径规划结果
     */
    @Override
    public GaodePathResponse getBicyclingPath(String origin, String destination) {
        // 构建完整请求URL
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl + bicyclingPath)
                .queryParam("origin", origin)
                .queryParam("destination", destination)
                .queryParam("key", gaodeKey)
                .build()
                .toUri();
//        log.info("调用高德骑行路径规划API: {}", uri);
        return restTemplate.getForObject(uri, GaodePathResponse.class);
    }

    @Override
    public GaodePathResponse getDrivingPath(String origin, String destination) {
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl + drivingPath)
                .queryParam("origin", origin)
                .queryParam("destination", destination)
                .queryParam("key", gaodeKey)
                .queryParam("extensions", "base")
                .build()
                .toUri();
        return restTemplate.getForObject(uri, GaodePathResponse.class);
    }

    @Override
    public GaodePathResponse getWalkingPath(String origin, String destination) {
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl + walkingPath)
                .queryParam("origin", origin)
                .queryParam("destination", destination)
                .queryParam("key", gaodeKey)
                .build()
                .toUri();
        return restTemplate.getForObject(uri, GaodePathResponse.class);
    }
}